package main;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import br.cin.stadium.middleware.network.config.NetConfig;

public class RegisterBroker {

	private ServerSocket serverSocket;
	private Socket socket;

	public RegisterBroker() {
		try {
			serverSocket = new ServerSocket(NetConfig.STADIUM_DIRECTOR_PORT_REGISTER);

		} catch (IOException e) {
			System.err.println("Cannot create the server socket on port:" + NetConfig.STADIUM_DIRECTOR_PORT_REGISTER + ".");
			e.printStackTrace();
			System.exit(-1);
		}
	}

	public void listen() {
		try {
			socket = serverSocket.accept();

		} catch (IOException e) {
			System.err.println("Cannot accept the connection on the server socket.");
			e.printStackTrace();
			System.exit(-1);
		}
	}

	public void close() {
		try {
			socket.close();
		} catch (IOException e) {
			System.err.println("Cannot close the socket.");
			e.printStackTrace();
			System.exit(-1);
		}
	}

	public String getClientIP() {
		String retorno = socket.getRemoteSocketAddress().toString();
		return retorno
				.substring(retorno.indexOf('/') + 1, retorno.indexOf(':'));
	}

	public byte[] getRequest() {
		InputStream input = null;
		int length = 0;

		try {
			while (length == 0) {
				input = socket.getInputStream();
				length = input.available();
			}

			byte bytes[] = new byte[length];
			input.read(bytes);

			return bytes;
		} catch (IOException e) {
			System.err.println("I/O Exception.");
			e.printStackTrace();
		}
		return null;
	}
}